<template>
  <div class="tag-selector">
    <el-select
      v-model="selectedTags"
      multiple
      filterable
      allow-create
      default-first-option
      :reserve-keyword="false"
      :placeholder="placeholder"
      :loading="loading"
      class="tag-select"
      @change="handleTagChange"
      @visible-change="handleVisibleChange"
    >
      <template #empty>
        <div class="empty-tags">
          <span>输入标签名称后按回车添加</span>
        </div>
      </template>
      
      <!-- 系统标签分组 -->
      <el-option-group
        v-if="systemTags.length > 0"
        label="系统标签"
        class="tag-option-group"
      >
        <el-option
          v-for="tag in systemTags"
          :key="`system-${tag.name}`"
          :label="tag.name"
          :value="tag.name"
          class="system-tag-option"
        >
          <div class="tag-option-content">
            <el-tag
              :color="tag.color"
              effect="dark"
              size="small"
              class="tag-preview"
            >
              {{ tag.name }}
            </el-tag>
            <span v-if="tag.description" class="tag-description">{{ tag.description }}</span>
          </div>
        </el-option>
      </el-option-group>
      
      <!-- 自定义标签提示 -->
      <el-option-group
        v-if="customTags.length > 0"
        label="自定义标签"
        class="tag-option-group"
      >
        <el-option
          v-for="tag in customTags"
          :key="`custom-${tag}`"
          :label="tag"
          :value="tag"
          class="custom-tag-option"
        >
          <div class="tag-option-content">
            <el-tag size="small" type="info" class="tag-preview">
              {{ tag }}
            </el-tag>
            <span class="tag-description text-muted">自定义标签</span>
          </div>
        </el-option>
      </el-option-group>
    </el-select>
    
    <!-- 已选标签展示 -->
    <div v-if="selectedTags.length > 0" class="selected-tags-display">
      <div class="tags-container">
        <div
          v-for="tagName in selectedTags"
          :key="tagName"
          class="tag-item"
        >
          <el-tag
            :color="getTagColor(tagName)"
            :type="isSystemTag(tagName) ? undefined : 'info'"
            effect="dark"
            size="small"
            closable
            @close="removeTag(tagName)"
          >
            <span v-if="isSystemTag(tagName)" class="tag-icon">✓</span>
            {{ tagName }}
          </el-tag>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { getModuleTags } from '@/api/tags'
import type { Tag } from '@/types/tag'

interface Props {
  modelValue: string[]
  moduleType?: string
  placeholder?: string
}

interface Emits {
  (e: 'update:modelValue', value: string[]): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  moduleType: '',
  placeholder: '请选择或输入标签'
})

const emit = defineEmits<Emits>()

const selectedTags = ref<string[]>([...props.modelValue])
const systemTags = ref<Tag[]>([])
const loading = ref(false)

// 自定义标签（不在系统标签中的）
const customTags = computed(() => {
  return selectedTags.value.filter(tag => !isSystemTag(tag))
})

// 加载系统标签
const loadSystemTags = async () => {
  if (!props.moduleType) {
    systemTags.value = []
    return
  }
  
  loading.value = true
  try {
    const tags = await getModuleTags(props.moduleType)
    systemTags.value = tags || []
  } catch (error) {
    console.error('加载系统标签失败:', error)
    systemTags.value = []
  } finally {
    loading.value = false
  }
}

// 判断是否为系统标签
const isSystemTag = (tagName: string): boolean => {
  return systemTags.value.some(tag => tag.name === tagName)
}

// 获取标签颜色
const getTagColor = (tagName: string): string => {
  const systemTag = systemTags.value.find(tag => tag.name === tagName)
  return systemTag?.color || '#909399'
}

// 处理标签变化
const handleTagChange = (value: string[]) => {
  selectedTags.value = value
  emit('update:modelValue', value)
}

// 移除标签
const removeTag = (tagName: string) => {
  const index = selectedTags.value.indexOf(tagName)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
    emit('update:modelValue', selectedTags.value)
  }
}

// 下拉框显示/隐藏
const handleVisibleChange = (visible: boolean) => {
  if (visible && props.moduleType) {
    loadSystemTags()
  }
}

// 监听模块类型变化
watch(() => props.moduleType, () => {
  if (props.moduleType) {
    loadSystemTags()
  }
}, { immediate: true })

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(selectedTags.value)) {
    selectedTags.value = [...newVal]
  }
}, { deep: true })

onMounted(() => {
  if (props.moduleType) {
    loadSystemTags()
  }
})
</script>

<style scoped>
.tag-selector {
  width: 100%;
}

.tag-select {
  width: 100%;
}

.empty-tags {
  padding: 8px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.tag-option-group {
  margin: 0;
}

.tag-option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tag-preview {
  flex-shrink: 0;
}

.tag-description {
  font-size: 12px;
  color: #909399;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.text-muted {
  color: #909399;
}

.selected-tags-display {
  margin-top: 8px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag-item {
  display: inline-flex;
  align-items: center;
}

.tag-icon {
  margin-right: 4px;
  font-size: 12px;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
  height: auto;
  line-height: 1.5;
}

:deep(.el-select-dropdown__item.is-selected) {
  background-color: #f5f7fa;
}

:deep(.el-option-group__title) {
  padding: 8px 12px;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}
</style>

